import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MonthlyStatisticsDialog extends JDialog {
    private JTextField yearMonthField;
    private JComboBox<String> typeComboBox;
    private JTextField categoryField;

    public MonthlyStatisticsDialog(JFrame owner) {
        super(owner, "月度统计", true);
        setSize(300, 200);
        setLocationRelativeTo(owner); // 居中显示
        setLayout(new BorderLayout());

        // 创建输入字段
        yearMonthField = new JTextField(10);
        typeComboBox = new JComboBox<>(new String[]{"总支出", "总收入"});
        categoryField = new JTextField(10);

        // 创建标签和输入字段
        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5); // 添加内边距

        gbc.gridx = 0;
        gbc.gridy = 0;
        inputPanel.add(new JLabel("年份与月份 (yyyy-MM):"), gbc);
        gbc.gridx = 1;
        inputPanel.add(yearMonthField, gbc);

        gbc.gridx = 0;
        gbc.gridy = 1;
        inputPanel.add(new JLabel("类型:"), gbc);
        gbc.gridx = 1;
        inputPanel.add(typeComboBox, gbc);

        gbc.gridx = 0;
        gbc.gridy = 2;
        inputPanel.add(new JLabel("类别:"), gbc);
        gbc.gridx = 1;
        inputPanel.add(categoryField, gbc);

        // 创建查询按钮
        JButton queryButton = new JButton("查询");
        queryButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String yearMonth = yearMonthField.getText().trim();
                String type = (String) typeComboBox.getSelectedItem();
                String category = categoryField.getText().trim();

                if (!validateYearMonth(yearMonth)) {
                    JOptionPane.showMessageDialog(MonthlyStatisticsDialog.this, "请输入有效的年份与月份格式 (yyyy-MM)。", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                List<String[]> results = getStatistics(yearMonth, type, category);
                if (!results.isEmpty()) {
                    new StatisticsTableDialog(results).setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(MonthlyStatisticsDialog.this, "没有找到符合条件的数据。", "提示", JOptionPane.INFORMATION_MESSAGE);
                }
            }
        });

        // 添加组件到对话框
        add(inputPanel, BorderLayout.CENTER);
        add(queryButton, BorderLayout.SOUTH);
    }

    private boolean validateYearMonth(String yearMonth) {
        try {
            String[] parts = yearMonth.split("-");
            if (parts.length != 2) {
                return false;
            }
            int year = Integer.parseInt(parts[0]);
            int month = Integer.parseInt(parts[1]);
            if (year < 0 || month < 1 || month > 12) {
                return false;
            }
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    private List<String[]> getStatistics(String yearMonth, String type, String category) {
        List<String[]> results = new ArrayList<>();
        String filePath = type.equals("总收入") ? "Gitzuoye/src/income" : "Gitzuoye/src/expenses";

        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            int index = 1;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length >= 4 && yearMonth.equals(parts[0].substring(0, 7))) {
                    if (category.isEmpty() || category.equals(parts[2])) {
                        results.add(new String[]{String.valueOf(index++), parts[0], parts[1], parts[2], parts[3]});
                    }
                }
            }
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this, "无法读取文件，请检查文件路径或权限。", "错误", JOptionPane.ERROR_MESSAGE);
        }

        return results;
    }

    // 内部类：统计结果表格对话框
    private class StatisticsTableDialog extends JDialog {
        private JTable table;

        public StatisticsTableDialog(List<String[]> data) {
            super(MonthlyStatisticsDialog.this, "统计结果", true);
            setSize(800, 600);
            setLocationRelativeTo(MonthlyStatisticsDialog.this); // 居中显示
            setLayout(new BorderLayout());

            // 创建表格模型
            String[] columnNames = {"序号", "日期", "金额", "类别", "备注"};
            DefaultTableModel model = new DefaultTableModel(columnNames, 0);

            // 填充表格数据
            for (String[] row : data) {
                model.addRow(row);
            }

            // 创建表格
            table = new JTable(model);
            table.setFillsViewportHeight(true);

            // 设置表格内容居中
            DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
            centerRenderer.setHorizontalAlignment(SwingConstants.CENTER);
            for (int i = 0; i < table.getColumnCount(); i++) {
                table.getColumnModel().getColumn(i).setCellRenderer(centerRenderer);
            }

            // 创建滚动面板
            JScrollPane scrollPane = new JScrollPane(table);

            // 添加滚动面板到对话框
            add(scrollPane, BorderLayout.CENTER);

            // 创建关闭按钮
            JButton closeButton = new JButton("关闭");
            closeButton.addActionListener(e -> dispose());

            // 添加关闭按钮到对话框
            add(closeButton, BorderLayout.SOUTH);
        }
    }
}